﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Toulr.Util.Security
{
    public class PasswordHelper
    {
        /// <summary>
        /// Generates the random password.
        /// </summary>
        /// <param name="len">The len.</param>
        /// <returns></returns>
        /// <Author>Tecky Lee</Author>
        /// <Date>2011/5/26 20:01</Date>
        public static string GenerateRandomPassword(int len)
        {
            if (len < 1)
            {
                throw new ArgumentOutOfRangeException("len", "生成的密码长度不能小于1");
            }
            int[] arrCharIndex = new int[len];

            for (int i = 0; i < arrCharIndex.Length; i++)
            {
                Random rand = new Random(i);
                arrCharIndex[i] = rand.Next(10 + 26 + 26);
            }
            StringBuilder sbPwd = new StringBuilder(arrCharIndex.Length);
            foreach (int index in arrCharIndex)
            {
                if (index < 10)
                {
                    sbPwd.Append(index);
                }
                else
                {
                    if ((index - 10) / 26 == 0)
                    {
                        sbPwd.Append((Char)(65 + (index - 10) % 26));
                    }
                    else
                    {
                        sbPwd.Append((Char)(97 + (index - 10) % 26));
                    }
                }
            }

            return sbPwd.ToString();
        }
    }
}
